package com.maikang.exammall.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Configuration {
    public List<SecurityScheme> securitySchemes() {
        return asList(new ApiKey("Auth Service Authorization", "token", "header"));
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select().
                apis(RequestHandlerSelectors.any()).
                paths(PathSelectors.any()).
                build().
                securitySchemes(securitySchemes()).
                securityContexts(securityContexts()).
                globalOperationParameters((operationParameters()));
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder().
                securityReferences(securityReferences()).
                forPaths(PathSelectors.any()).build());
        return securityContexts;
    }

    private List<SecurityReference> securityReferences() {
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = new AuthorizationScope("global", "accessEverything");
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Auth Service Authorization", authorizationScopes));
        return securityReferences;
    }

    private List<Parameter> operationParameters() {
        return asList(new ParameterBuilder().name("token")
        .description("user token").modelRef(new ModelRef("string"))
                .parameterType("header").
                        required(false).build());
    }

}
